﻿using System;
using System.IO.Ports;
using System.Text;
using System.Threading;

namespace yDevice.ExpanderDevice
{
    /// <summary>
    /// 爱华仪器噪音设备
    /// </summary>
    public class NoiseDev
    {
        SerialPort serialPort;
        string portName;
        int baudRate;

        /// <summary>
        /// 实时噪音
        /// </summary>
        public double RealNoise;

        public NoiseDev(string portName, int baudRate = 115200)
        {
            this.portName = portName;
            this.baudRate = baudRate;
        }

        public bool Connected()
        {
            serialPort = new SerialPort(portName, baudRate);
            serialPort.DataReceived += DataReceived;
            try
            {
                serialPort.Open();
                if (serialPort.IsOpen)
                {
                    byte[] cmd = new byte[4] { 0x41, 0x57, 0x41, 0x42 }; // 爱华仪器噪音设备实时读取数据开启命令
                    serialPort.Write(cmd, 0, 4);
                }
            }
            catch { }
            return serialPort.IsOpen;
        }

        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort.IsOpen)
            {
                try
                {
                    Thread.Sleep(100);
                    byte[] data = new byte[serialPort.BytesToRead];
                    serialPort.Read(data, 0, data.Length);
                    string indata = Encoding.ASCII.GetString(data);
                    if (indata.Substring(0, 12).Equals("AWAB;[data];"))
                    {
                        RealNoise = Convert.ToDouble(indata.Substring(87, 4));
                    }
                }
                catch
                {
                }
            }
        }
    }
}
